package com.zllkj.mm.module.home.fragments

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity
import com.zllkj.mm.R
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseFragment
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.model.entity.AddressBeanVo
import com.zllkj.mm.util.common.AppUtils
import kotlinx.android.synthetic.main.fragment_address_detail.*
import kotlinx.android.synthetic.main.fragment_address_detail.view.*
import kotlinx.android.synthetic.main.item_address_list.view.*
import java.util.*


class AddressModifyFragment(val addressId:String) : BaseTitleFragment() {
    var city = ""
    var detailAddress = ""
    var district = ""
    var province = ""
    var receiverPhone = ""
    var receiverName = ""

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_address_detail
    }

    override fun loadData() {
        super.loadData()


        if (addressId == ""){
            setCommonTitle("新增地址")
        } else{
            loadAddressInfo()
            setCommonTitle("编辑地址")
        }
        mRootView.btn_modify_address_confirm.setOnClickListener {
            if (addressId == "") {
                addAddress()
            } else {
                modifyAddress()
            }
            removeFragment()
        }

        mRootView.ed_modify_address_area.setOnClickListener {
            val picker = AddressPicker(requireActivity())

            picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
            if (province != null) {
                picker.setDefaultValue(province, city, district)
            } else {
                picker.setDefaultValue("广东省", "广州市", "天河区")
            }
            picker.setOnAddressPickedListener(object : OnAddressPickedListener {
                override fun onAddressPicked(province: ProvinceEntity?, city: CityEntity?, county: CountyEntity?) {
                    province?.let {
                        this@AddressModifyFragment.province = province?.name
                    }
                    city?.let {
                        this@AddressModifyFragment.city = it.name
                    }
                    county?.let {
                        this@AddressModifyFragment.province = it.name
                    }
                    mRootView.ed_modify_address_area.text = this@AddressModifyFragment.province  + this@AddressModifyFragment.city +  this@AddressModifyFragment.province

                }

            })
            picker.show()
        }
    }

    override fun onResume() {
        super.onResume()

    }

    fun addAddress(){
        addSubscribe(RetrofitHelper.getInstance().addressApi.addNewAddress((HashMap<String, Any>().apply {
            this["city"] = city
            this["defaultStatus"] = if (mRootView.switch_default_address.isChecked) 1 else 0
            this["detailAddress"] = mRootView.ed_modify_address_detail_address.text.toString()
            this["district"] = district
            this["province"] = province
            this["receiverPhone"] = mRootView.ed_modify_address_phone.text.toString()
            this["receiverName"] = mRootView.ed_modify_address_name.text.toString()
            this["userAddressId"] = addressId

        })).compose<AddressBeanVo>(RxHelper.defaultHandleResult<AddressBeanVo>()).subscribe(object : ProgressSubscriber<Any>(context){
            override fun onSucc(t: Any?) {
                requireContext().sendBroadcast(Intent(BaseFragment.ACTION_FRAGMENT_UPDATE).apply {
                    putExtra(AppUtils.KEY_OF_ADDRESS_UPDATE,true)
                })
                removeFragment()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)

            }
        }))
    }

    fun modifyAddress(){
        addSubscribe(RetrofitHelper.getInstance().addressApi.editAddress((HashMap<String, Any>().apply {
            this["city"] = city
            this["defaultStatus"] = if (mRootView.switch_default_address.isChecked) 1 else 0
            this["detailAddress"] = mRootView.ed_modify_address_detail_address.text.toString()
            this["district"] = district
            this["province"] = province
            this["receiverPhone"] = mRootView.ed_modify_address_phone.text.toString()
            this["receiverName"] = mRootView.ed_modify_address_name.text.toString()
            this["userAddressId"] = addressId

        })).compose<Any>(RxHelper.defaultHandleResult<Any>()).subscribe(object : ProgressSubscriber<Any>(context){
            override fun onSucc(t: Any?) {
                    requireContext().sendBroadcast(Intent(BaseFragment.ACTION_FRAGMENT_UPDATE).apply {
                        putExtra(AppUtils.KEY_OF_ADDRESS_UPDATE,true)
                    })
                   removeFragment()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)

            }
        }))
    }

    override fun onKeyBoardShow() {
        super.onKeyBoardShow()
        mRootView.btn_modify_address_confirm.visibility = View.GONE
    }

    override fun onKeyBoardHide() {
        super.onKeyBoardHide()
        Handler().postDelayed({mRootView.btn_modify_address_confirm.visibility = View.VISIBLE},300)

    }

    fun loadAddressInfo(){
        addSubscribe(RetrofitHelper.getInstance().addressApi.findAddressById((HashMap<String, Any>().apply {
            this["userAddressId"] = addressId
        })).compose<AddressBeanVo>(RxHelper.defaultHandleResult<AddressBeanVo>()).subscribe(object : ProgressSubscriber<AddressBeanVo>(context){
            override fun onSucc(t: AddressBeanVo) {
                city = t?.city
                receiverName = t?.receiverName
                province = t?.province
                district = t?.district
                detailAddress = t?.detailAddress
                mRootView.ed_modify_address_name.setText(t?.receiverName)
                mRootView.ed_modify_address_phone.setText(t?.receiverPhone)
                mRootView.ed_modify_address_area.setText(t?.city + " " + t?.province + " " + t?.district )
                mRootView.ed_modify_address_detail_address.setText(t?.detailAddress)

                if (t?.defaultStatus == 1) {
                    mRootView.switch_default_address.isChecked = true
                }
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }


}